const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { TOKEN_TIMEOUT, JWT_SECRET_KEY } = require('../../config')
const loginHandler = (req, res) => {
    const userInfo = req.body
    const sql = 'SELECT * FROM users WHERE username = ? AND isDelete = 0';


    req.myDB.query(sql, [userInfo.username], (err, dbRes) => {

        if (err) {
            return res.err(err)
        }
        if (dbRes.length) {

            //和数据库加密的比较
            const isRight = bcrypt.compareSync(userInfo.password, dbRes[0].password)

            if (isRight) {
                const token = jwt.sign({ id: dbRes[0].id, username: userInfo.username }, JWT_SECRET_KEY, { expiresIn: TOKEN_TIMEOUT })
                res.success('登录成功！', 'Bearer ' + token)
            } else {
                res.success('密码错误！')
            }

        } else {
            res.success('该用户尚未注册！')
        }
    })
}
const registerHandler = (req, res) => {
    const { body, myDB } = req
    const sql = 'SELECT * FROM users WHERE username = ?'
    myDB.query(sql, [body.username], (err, dbRes) => {
        if (err) {
            return res.err(err)
        }
        if (dbRes.length) {
            return res.success('用户名已存在!')
        } else {
            body.password = bcrypt.hashSync(body.password, 10)
            myDB.query('INSERT INTO users SET ?', body, (err, dbRes) => {
                if (err) return res.err(err)
                return res.success(dbRes.affectedRows === 1 ? '注册成功!' : '注册失败')
            })
        }

    })




}

module.exports = {
    loginHandler,
    registerHandler
}